/*
 * Copyright (C) 2010 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.ui;

import android.app.Dialog;
import android.app.LocalActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.TabHost.TabSpec;
import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.download.DownloadManager;
import com.mol.market.common.network.ApiAsyncTask.ApiRequestListener;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.*;
import com.mol.market.common.util.DBUtils.DbOperationResultListener;
import com.mol.market.common.util.DialogUtil.WarningDialogListener;
import com.mol.market.common.vo.BuyLog;
import com.mol.market.common.vo.DownloadInfo;
import com.mol.market.common.vo.DownloadItem;
import com.mol.market.common.vo.ProductDetail;
import com.mol.market.common.widget.BaseTabActivity;
import com.mol.market.common.widget.MarqueeTextView;
import com.mol.market.widget.SlotMachinesWidget;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 商品详细页 <br>
 * 1 - 通过包名访问<br>
 * 2 - 通过产品ID访问(Google Market)<br>
 * 
 * @author andrew
 * @date 2011-3-14
 * @since Version 0.6.2
 */
public class ProductDetailActivity extends BaseTabActivity implements ApiRequestListener {

    /**
     * 开始下载应用命令广播
     */
    public static final String ACTION_DOWNLOAD = "download";

    private static final String TAB_INFO = "info";
    private static final String TAB_COMMENT = "comment";

    private ProductDetail mProduct;
    private TabHost mTabHost;
    private boolean mIsRecommend;


    private BroadcastReceiver mActionReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            Object param = intent.getSerializableExtra(Constants.EXTRA_PRDUCT_DETAIL);
            if (param == null) {
                return;
            }

            ProductDetail product = (ProductDetail) param;
            if (!product.getPackageName().equals(mProduct.getPackageName())) {
                return;
            }

            mProduct.isPendingDownload = product.isPendingDownload;

            // 接收到下载命令
            download();
        }
    };
    
    /**
     * fix bug:
     *  机锋市场客户端关闭状态，通过老虎机进入此页面，按Home，再点老虎机时，
     *  进入的还是此页面。原因在于此页面没有destroy，再启动时直接进入了onResume.
     *  @author Chaos 
     * 2012-9-11
     */

    private BroadcastReceiver mDestroyReceiver = new BroadcastReceiver() {
        
        @Override
        public void onReceive(Context context, Intent intent) {
            int flag = intent.getIntExtra(SlotMachinesWidget.INTENT_EXTRA, -1);
            if(flag == SlotMachinesWidget.EXTRA_HOMETABACTIVITY){
                //如果是进入首页，则不销毁这个页面
                return ;
            }
            finish();
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_product_detail_layout);

        if (!mSession.mIsKeyboardAvailable) {
            // 当用户没有硬键盘时，强制使用竖屏幕
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        
        final Intent intent = getIntent();
        mProduct = (ProductDetail) intent.getSerializableExtra(Constants.EXTRA_PRDUCT_DETAIL);
        mIsRecommend = intent.getBooleanExtra(Constants.EXTRA_PRODUCT_RECOMMEND, false);
        initTopBar(mProduct);
        initTab(mProduct);
        boolean isBuy = intent.getBooleanExtra(Constants.IS_BUY, false);
        if (isBuy) {
            showDialog(DIALOG_PURCHASE);
        }

        IntentFilter filter = new IntentFilter(ACTION_DOWNLOAD);
        registerReceiver(mActionReceiver, filter);
        IntentFilter filterDestroy = new IntentFilter(SlotMachinesWidget.ACTION_DESTROY_START);
        registerReceiver(mDestroyReceiver, filterDestroy);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mActionReceiver);
        unregisterReceiver(mDestroyReceiver);
        LocalActivityManager lam = getLocalActivityManager();
        lam.removeAllActivities();
    }

    /*
     * 初始化TopBar
     */
    private void initTopBar(final ProductDetail product) {

        TextView bg = (TextView) findViewById(R.id.topbar);
        bg.setBackgroundResource(ThemeManager.getResource(mSession, ThemeManager.KEY_TOP_BAR_BG));

        final ImageView ivIcon = (ImageView) findViewById(R.id.iv_icon);
        ImageUtils.download(getApplicationContext(), product.getIconUrl(), ivIcon,
                R.drawable.loading_icon, true, false);

        final MarqueeTextView tvName = (MarqueeTextView) findViewById(R.id.tv_name);
        tvName.setTextAppearance(getApplicationContext(),
                ThemeManager.getResource(mSession, ThemeManager.KEY_TOP_TITLE_TEXT));
        if (mSession.getTheme() == ThemeManager.THEME_TYPE_DARK) {
            tvName.setShadowLayer(0.1f, 0, -2.0f, Color.BLACK);
        }
        tvName.setText(product.getName());

        final ImageButton btnShare = (ImageButton) findViewById(R.id.btn_operation);
        btnShare.setImageResource(ThemeManager
                .getResource(mSession, ThemeManager.KEY_TOP_BAR_SHARE));
        btnShare.setBackgroundResource(ThemeManager.getResource(mSession,
                ThemeManager.KEY_TOP_BAR_BTN_BG));
        btnShare.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Utils.trackEvent(getApplicationContext(), Constants.GROUP_8, Constants.DETAIL_SHARE);
                Utils.share(getCurrentActivity(), mProduct.getName(), mProduct.getPid());
            }
        });
    }

    /*
     * 初始化Tab页面
     */
    private void initTab(ProductDetail product) {

        mTabHost = getTabHost();
        mTabHost.getTabWidget().setPadding(mSession.mTabMargin110, 0, mSession.mTabMargin9, 0);
        mTabHost.setup();
        FrameLayout fl = (FrameLayout) mTabHost.findViewById(R.id.tab_frame_layout);
        fl.setBackgroundResource(ThemeManager.getResource(mSession, ThemeManager.KEY_TAB_BG));

        {
            TabSpec tab = mTabHost.newTabSpec(TAB_INFO);
            tab.setIndicator(Utils.createTabView(getApplicationContext(), mSession,
                    getString(R.string.label_description), -1, null));
            Intent i = new Intent(this, ProductInfoActivity.class);
            i.putExtra(Constants.EXTRA_PRDUCT_DETAIL, product);
            tab.setContent(i);
            mTabHost.addTab(tab);
        }

        {
            TabSpec tab = mTabHost.newTabSpec(TAB_COMMENT);
            tab.setIndicator(Utils.createTabView(getApplicationContext(), mSession,
                    getString(R.string.comment_lab), 1, null));

            Intent i = new Intent(this, ProductCommentActivity.class);
            i.putExtra(Constants.EXTRA_PRDUCT_DETAIL, product);
            tab.setContent(i);
            mTabHost.addTab(tab);
        }
        mTabHost.setCurrentTab(0);
    }

    public void onSuccess(int method, Object obj) {
        switch (method) {
        case MarketAPI.ACTION_GET_DOWNLOAD_URL:
            DownloadItem info = (DownloadItem) obj;

            if (mProduct.isPendingDownload) {
                startWaitingDownload(info);
            } else {
                startDownload(info);
            }
            break;

        case MarketAPI.ACTION_PURCHASE_PRODUCT:
            // 购买成功，同步购买记录
            BuyLog buyLog = new BuyLog();
            buyLog.pId = mProduct.getPid();
            buyLog.packageName = mProduct.getPackageName();
            DBUtils.insertBuyLog(getApplicationContext(), buyLog);
            MarketAPI.getDownloadUrl(this, this, mProduct.getPid(), mProduct.getSourceType());
            break;
        }
    }

    public void onError(int method, int statusCode) {
        switch (method) {
        case MarketAPI.ACTION_GET_DOWNLOAD_URL:
            Utils.makeEventToast(getApplicationContext(),
                    getString(R.string.alert_no_download_url), false);
            break;
        case MarketAPI.ACTION_PURCHASE_PRODUCT:
            if (219 == statusCode) {
                // NoEnoughCredit
                if (!isFinishing()) {
                    showDialog(DIALOG_NO_BALANCE);
                }
            } else if (212 == statusCode) {
                // 密码错误
                Utils.makeEventToast(getApplicationContext(),
                        getString(R.string.hint_purchase_password_error), false);
            } else {
                // other error
                Utils.makeEventToast(getApplicationContext(),
                        getString(R.string.hint_purchase_failed), false);
            }
            break;
        default:
            break;
        }
    }

    /**
     * 开始下载任务
     */
    private void startDownload(DownloadItem info) {
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(info.url));
        request.setPackageName(mProduct.getPackageName());
        request.setTitle(mProduct.getName());
        request.setIconUrl(mProduct.getIconUrl());
        request.setMD5(info.fileMD5);
        request.setSourceType(com.mol.market.common.download.Constants.DOWNLOAD_FROM_MARKET);
        mSession.getDownloadManager().enqueue(getApplicationContext(), request, null);

        if (mIsRecommend) {
            // 首页推荐带来的直接下载量统计
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_8,
                    String.format(Constants.DETAIL_RECOMMEND_APP, mProduct.getName()));
        }
        Utils.makeEventToast(getApplicationContext(), getString(R.string.alert_start_download),
                false);

        Intent i = getIntent();
        String nid = i.getStringExtra(Constants.EXTRA_APP_NID);
        String rule = i.getStringExtra(Constants.EXTRA_APP_RULE);
        if (!TextUtils.isEmpty(nid)) {
            MarketAPI.reportIftttResult(getApplicationContext(), mProduct.getPid(), nid, rule,
                    Constants.REPORT_TYPE_DOWNLOAD);
        }
    }

    /**
     * 加入下载队列
     */
    private void startWaitingDownload(DownloadItem info) {
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(info.url));
        request.setPackageName(mProduct.getPackageName());
        request.setTitle(mProduct.getName());
        request.setIconUrl(mProduct.getIconUrl());
        request.setMD5(info.fileMD5);
        request.setSourceType(com.mol.market.common.download.Constants.DOWNLOAD_FROM_MARKET);
        mSession.getDownloadManager().enqueueWaitRequest(request, null);
        Utils.makeEventToast(getApplicationContext(), getString(R.string.alert_waiting_download),
                true);
    }

    /**
     * 开始下载任务
     */
    public void download() {

        if (Constants.PAY_TYPE_PAID == mProduct.getPayCategory()) {

            if (!mSession.isLogin()) {
                // 收费应用必须登录
                Intent loginIntent = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(loginIntent);
                return;
            }

            DBUtils.isBought(getApplicationContext(), mProduct.getPid(),
                    new DbOperationResultListener<Boolean>() {
                        @Override
                        protected void onQueryResult(Boolean result) {
                            if (!result && !isFinishing()) {
                                showDialog(DIALOG_PURCHASE);
                            } else {
                                excuteDownload();
                            }
                        }
                    });
        } else {
            // 免费应用
            excuteDownload();
        }
    }

    /*
     * 根据下载状态进行下载处理
     */
    private void excuteDownload() {

        ConcurrentHashMap<String, DownloadInfo> list = mSession.getDownloadingList();

        DownloadInfo info = list.get(mProduct.getPackageName());
        boolean isAlreadyInTask = (info != null) && Utils.isFileExist(info.mFilePath);
        if (isAlreadyInTask) {
            // 下载中
            Utils.makeEventToast(getApplicationContext(),
                    getString(R.string.warning_comment_later), false);
            return;
        }

        if (mSession.getInstalledApps().contains(mProduct.getPackageName())) {
            // 升级签名检查
            if (!Utils.isSameSign(getApplicationContext(), mProduct.getPackageName(),
                    mProduct.getRsaMd5())) {

                if (!isFinishing()) {
                    DialogUtil.createComfirmDownloadDialog(this, true,
                            new WarningDialogListener() {

                                @Override
                                public void onWarningDialogOK(int id) {
                                    // 开始下载
                                    if (mSession.addDownload(mProduct.getPackageName())) {
                                        MarketAPI.getDownloadUrl(getApplicationContext(),
                                                ProductDetailActivity.this, mProduct.getPid(),
                                                mProduct.getSourceType());
                                    }

                                }

                                @Override
                                public void onWarningDialogCancel(int id) {
                                }

                            }).show();
                }
                return;
            }
        }
        // 开始下载
        if (mSession.addDownload(mProduct.getPackageName())) {
            MarketAPI.getDownloadUrl(getApplicationContext(), ProductDetailActivity.this,
                    mProduct.getPid(), mProduct.getSourceType());
        }
    }

    private final static int DIALOG_PURCHASE = 1;
    private final static int DIALOG_NO_BALANCE = 2;


    protected Dialog onCreateDialog(int id) {
        switch (id) {
//        case DIALOG_PURCHASE:
//            return DialogUtil.newEnsurePurchaseDialog(this, id,
//                    getString(R.string.hint_purchase, mProduct.getPrice()));
//        case DIALOG_NO_BALANCE:
//            return DialogUtil.newInsufficientBalanceDialog(this, id,
//                    getString(R.string.warning_no_balance));
        default:
            break;
        }
        return null;
    }

    /**
     * 购买商品
     */
    public void purchaseProduct(String password) {
        MarketAPI.purchaseProduct(this, this, mProduct.getPid(), password);
    }

    /**
     * 前往充值页
     */
    public void gotoDepositPage() {
        final String type = mSession.getDefaultChargeType();
        if (type == null) {
            final Intent intent = new Intent(getApplicationContext(), ChargeTypeListActivity.class);
            intent.putExtra("payment", mProduct.getPrice());
            startActivity(intent);
        } else {
            final Intent intent = new Intent(getApplicationContext(), PayMainActivity.class);
            intent.putExtra("type", type);
            intent.putExtra("payment", mProduct.getPrice());
            startActivity(intent);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        final MenuItem item = menu.add(0, 0, 0, getString(R.string.alert_safe));
        item.setIcon(R.drawable.ic_safe);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case 0:
            Intent i = new Intent(getApplicationContext(), SafeActivity.class);
            startActivity(i);
            return true;
        }
        return false;
    }
}